'use strict';

import { invitationModel } from "../model/invitation";
import { ServiceBase, Exceptions } from '../kalend';
import { usertokenService } from "./usertoken";
var moment = require('moment');

class InvitationService extends ServiceBase {
    constructor() {
        super(invitationModel)
    }
    async queryCount(uid: any) {
        return this.count({ inviter: uid });
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const token = params.token;
        if (!token) {
            throw Exceptions.notoken();
        }
        let userid = (await usertokenService.getToken(token)).userid;
        let data: any = await this.queryPagination(offset, limit, {
            filter: { $or: [{ inviter: userid }, { agent: userid }], isdel: { $ne: true } },
            populateOptions: {
                path: 'customerid',
                select: 'nickname headimg ismember issupermember isdiamondmember'
            },
            select: 'customerid createTime isupvip mealbalance',
            sort: { createTime: -1 }
        });
        data.rows = data.rows.map((item: any) => {
            if (item.customerid) {
                item.nickname = item.customerid.nickname;
                item.headimg = item.customerid.headimg;
                item.ismember = item.customerid.ismember;
                item.issupermember = item.customerid.issupermember;
                item.isdiamondmember = item.customerid.isdiamondmember;
            }
            delete item.customerid;
            item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm');
            item.status = item.isupvip ? '邀请成功' : '邀请中';
            if (item.isupvip && item.mealbalance >= 0) {
                item.mealbalance = "餐币+" + item.mealbalance;
            }
            return item;
        });
        const count = await this.count({ $or: [{ inviter: userid }, { agent: userid }], isupvip: true, isdel: { $ne: true } });

        const superdata = (await invitationModel.aggregate([
            {
                $match: {
                    isupvip: true,
                    $or: [{ inviter: userid }, { agent: userid }],
                    isdel: { $ne: true }
                }
            },
            {
                $lookup: {
                    from: "customer_accounts",
                    localField: "customerid",
                    foreignField: "_id",
                    as: "user"
                }
            },
            {
                $unwind: "$user"
            },
            {
                $match: {
                    "user.issupermember": true
                }
            },
            {
                $count: "num"
            }
        ]));
        let supermembercount = 0;
        if (superdata && superdata.length > 0) {
            supermembercount = superdata[0].num;
        }
        const diamonddata = (await invitationModel.aggregate([
            {
                $match: {
                    isupvip: true,
                    $or: [{ inviter: userid }, { agent: userid }],
                    isdel: { $ne: true }
                }
            },
            {
                $lookup: {
                    from: "customer_accounts",
                    localField: "customerid",
                    foreignField: "_id",
                    as: "user"
                }
            },
            {
                $unwind: "$user"
            },
            {
                $match: {
                    "user.isdiamondmember": true
                }
            },
            {
                $count: "num"
            }
        ]));
        let diamondmembercount = 0;
        if (diamonddata && diamonddata.length > 0) {
            diamondmembercount = diamonddata[0].num;
        }
        data.totaltitle = `成功邀请${count}人`;
        if (count - supermembercount - diamondmembercount > 0) {
            data.totaltitle += `，黄金会员${count - supermembercount - diamondmembercount}人`;
        }
        if (supermembercount > 0) {
            data.totaltitle += `，白金会员${supermembercount}人`;
        }
        if (diamondmembercount > 0) {
            data.totaltitle += `，钻石会员${diamondmembercount}人`;
        }
        data.totaltitle += '。';
        //data.totaltitle = `成功邀请${count}人，黄金会员${count - supermembercount - diamondmembercount}人，白金会员${supermembercount}人，钻石会员${diamondmembercount}`
        return data;
    }

    async updatestate(uid: any, inviter: any, upmoney: any, mealbalance: any) {
        const data = await this.querySingle({ customerid: uid, inviter: inviter });
        if (data) {
            this.update(data._id, {
                isupvip: true,
                upmoney: upmoney,
                isgive: true,
                mealbalance: mealbalance
            });
        }
    }

    async querylist(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const userid = params.uid;
        const status = params.status;
        const starttime = params.starttime;
        const endtime = params.endtime;

        let filter: any = {};
        if (userid) {
            filter.inviter = userid;
        }
        if (status != 'all') {
            filter.isupvip = status;
        }
        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        let data = await this.queryPagination(offset, limit, {
            filter: filter,
            populateOptions: [{
                path: 'customerid',
                select: 'nickname phone'
            }, {
                path: 'inviter',
                select: 'nickname phone'
            }]
        });
        data.rows = data.rows.map((item) => {
            if (item.customerid) {
                item.nickname = item.customerid.nickname;
                item.phone = item.customerid.phone;
                // if (item.customerid.phone) {
                //     item.phone = item.customerid.phone.substring(0, 3) + '****' + item.customerid.phone.substring(7, item.customerid.phone.length);
                // }
            }
            if (item.inviter) {
                item.invername = item.inviter.nickname;
                item.inverphone = item.inviter.phone;
            }
            delete item.customerid;
            delete item.inviter;

            item.updateTime = moment(item.createTime).format('YYYY-MM-DD HH:mm');
            item.status = item.isgive ? '邀请成功' : '邀请中';
            if (item.mealbalance) {
                item.mealbalance = "+" + item.mealbalance;
            }

            return item;
        });
        return data;
    }
}

export const invitationService = new InvitationService();